package com.briup.cms.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.briup.cms.domain.User;
import com.briup.cms.service.IUserService;
import com.briup.cms.utils.JwtUtil;
import com.briup.cms.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Wrapper;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shaoyb
 * @program: 1101cms
 * @description 登录模块，jwt引入后，额外分离出来的
 * @create 2022/11/3 11:54
 **/
@Api(tags = "登录模块")
@RestController
public class LoginController {

    @Autowired
    private IUserService userService;

    @ApiOperation(value = "登录", notes = "需要提供用户名和密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", paramType = "form", dataType = "String", required = true, defaultValue = "tom"),
            @ApiImplicitParam(name = "password", paramType = "form", dataType = "String", required = true, defaultValue = "000")
    }) //Post请求 + form提交 + consumes设置表单字符串
    @PostMapping(value = "/login", consumes = "application/x-www-form-urlencoded")
    public Result login(String username, @RequestParam("password") String passwd) {
        //根据用户名和密码查询 用户
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>();
        lqw.eq(User::getUsername, username).eq(User::getPassword,passwd);
        User user = userService.getOne(lqw);

        //准备map集合放入 用户信息
        Map<String,Object> info = new HashMap<>();
        info.put("id",user.getId());
        info.put("username",user.getUsername());
        //签发token
        String token = JwtUtil.sign(user.getUsername(), info);

        return Result.success("token: " + token);
    }

}
